import React, { Component } from 'react';
import { View, Animated, Text, StyleSheet, Easing, TouchableHighlight, Image, Platform, Dimensions, TouchableOpacity } from 'react-native';
import PropTypes from 'prop-types';
import Label from '../label/index';
import Color from '../../config/theme/standard/color';

import {getMarqueeStyle} from './MarqueeStyle';
import Variables from '../../config/theme/styles/index';

export default class Marquee extends Component {

    constructor(props) {
        super(props);
        this.state = {
            translateX: new Animated.Value(0),
            translateY: new Animated.Value(0),
            isClose: false,
            textAllWidth:0,
            isWideScreen: false
        };
        this.firstEx = true;
        this.continue = true;
        this.animationRunning = false;     //声明一个标识，动画开启之后就置为true
    }
    componentDidMount() {
        // 适配鸿蒙折叠屏动态更新组件
        this.addEventListenerScreenWidth = Dimensions.addEventListener('change', this.setIsWideScreen)
    }
    componentWillUnmount() {
        // 适配鸿蒙折叠屏动态更新组件
        if (this.addEventListenerScreenWidth) {
            this.addEventListenerScreenWidth = null
        }
    }
    setIsWideScreen = () => {
        const screenWidth = Dimensions.get('window').width;
        if (screenWidth) {
            this.setState({
                isWideScreen: screenWidth > 500 && screenWidth < 800
            })
        }
    }

    componentDidUpdate(prevProps) {
        if (prevProps.scroll != this.props.scroll) {
            if (this.props.scroll) {
                if (prevProps.direction == 'vertical') {
                    if (prevProps.text) {
                        if (prevProps.showTwoLine) {
                            this.startYAnimate(0, prevProps.text.length / 2);
                        } else {
                            this.startYAnimate(0, prevProps.text.length);
                        }
                    } else if (prevProps.scrollComponent) {
                        if (prevPropsshowTwoLine) {
                            this.startYAnimate(0, prevProps.scrollComponent.length / 2);
                        } else {
                            this.startYAnimate(0, prevProps.scrollComponent.length);
                        }
                    }
                } else {
                    this.startXAnimate();
                }
            } else {
                if (prevProps.direction == 'vertical') {
                    this.continue = false;
                    this.state.translateY.setValue(0);
                } else {
                    this.continue = false;
                    this.state.translateX.setValue(0);
                }
            }
        }
    }

    bgViewWOnLayout(e) {
        this.bgWidth = e.nativeEvent.layout.width;
        if (this.textWidth && this.props.scroll) {
            this.startXAnimate();
        }
    }

    textWOnLayout(e) {
        this.textWidth = e.nativeEvent.layout.width;
        if (this.bgWidth && this.props.scroll) {
            this.startXAnimate();
        }
    }
    textLayout(e){
        this.state.textAllWidth = this.state.textAllWidth + e.nativeEvent.layout.width + 16 ;
    }

    textHOnLayout(e) {
        this.textHeight = e.nativeEvent.layout.height;
        if (this.props.scroll) {
            if (this.props.text) {
                if (this.props.showTwoLine) {
                    this.startYAnimate(0, this.props.text.length / 2);
                } else {
                    this.startYAnimate(0, this.props.text.length);
                }
            } else if (this.props.scrollComponent) {
                if (this.props.showTwoLine) {
                    this.startYAnimate(0, this.props.scrollComponent.length / 2);
                } else {
                    this.startYAnimate(0, this.props.scrollComponent.length);
                }
            }
        }
    }

    //水平方向滚动
    startXAnimate() {
        let duration = 4000;
        let delay = 0;
        if (this.props.duration) {
            duration = this.props.duration * 1000;
        }
        if (this.firstEx) {
            delay = 0;
        } else if (this.props.delay) {
            delay = this.props.delay * 1000;
        }

        this.state.translateX.setValue(this.bgWidth);
        Animated.timing(this.state.translateX, {
            toValue: this.textWidth > this.state.textAllWidth ? -this.textWidth : -this.state.textAllWidth,
            useNativeDriver:true,
            duration: duration,
            Easing: Easing.linear,
            delay: delay,
            isInteraction: this.props.isInteraction
        }).start(() => {
            //水平滚动第一次不需要延迟
            this.firstEx = false;
            //循环动画
            if (this.continue) {
                this.startXAnimate();
            }
        })
        // 横向滚动开始置为true，防止折叠屏改变屏幕宽度后再次触发onlayout事件
        this.animationRunning = true
    }
    
    //垂直方向滚动
    startYAnimate(index, count) {
        let duration = 500;
        let delay = 3000;
        let scrollH = 44;

        if (this.props.duration) {
            duration = this.props.duration * 1000;
        }
        if (this.props.delay) {
            delay = this.props.delay * 1000;
        }
        if (this.props.showTwoLine) {
            scrollH = 64;
        }
        index++;
        Animated.timing(this.state.translateY, {
            useNativeDriver: true,
            toValue: -scrollH * index,
            duration: duration,
            Easing: Easing.linear,
            delay: delay,
            isInteraction: this.props.isInteraction
        }).start(() => {
            if (index >= count) {
                index = 0;
                this.state.translateY.setValue(0);
            }
            //循环动画
            if (this.continue) {
                this.startYAnimate(index, count);
            }
        })
         // 纵向滚动开始置为true，防止折叠屏改变屏幕宽度后再次触发onlayout事件
         this.animationRunning = true
    }

    _iconRightPress() {
        if (this.props.rightIconFunc) {
            this.props.rightIconFunc();
        }
    }

    _iconLeftPress() {
        if (this.props.leftIconFunc) {
            this.props.leftIconFunc();
        }
    }

    _textFunc(index) {
        if (this.props.textFunc) {
            this.props.textFunc(index);
        }
    }


    _close() {
        this.setState({ isClose: true });
    }



    render() {
        let { styles , marqueeStyle} = getMarqueeStyle(Variables);
        let { leftIcon, showLine, text, textColor, scrollComponent,
            rightIcon, showClose, backgroundColor, direction, showTwoLine,
            titleStyle, titleContainerStyle, scroll, titleFontSize, fontFamily, fontWeight, clickDisable
        } = this.props;
        let { isClose, translateX, translateY } = this.state;
        let conStyle = [styles.container];
	    let conWidth = this.props.conWidth || Dimensions.get('window').width;
        let containerWidth = conWidth;
        if (backgroundColor) {
            conStyle.push({ backgroundColor });
            conStyle.push({ width: conWidth });
        }
        let bgView = [styles.bgView];
        //左侧图标区域
        let leftArea;
        let leftIconCon = [styles.leftIconCon];
        let scrollWidth = containerWidth;
        if (leftIcon) {
            if (showClose || rightIcon) {
                if (showTwoLine) {
                    scrollWidth = scrollWidth - 121;
                } else {
                    scrollWidth = scrollWidth - 115;
                }
            } else {
                if (showTwoLine) {
                    scrollWidth = scrollWidth - 81;
                } else {
                    scrollWidth = scrollWidth - 75;
                }
            }
            if (showLine) {
                leftIconCon.push({ borderRightWidth: 1 });
                leftIconCon.push({ borderColor: Color.border });
                leftIconCon.push({ marginRight: 10 });
                scrollWidth = scrollWidth - 10;
            }
            leftArea = (<View style={[leftIconCon, { width: showTwoLine ? 66 : 60 }]}>
                <TouchableHighlight underlayColor='transparent' activeOpacity={0.7}
                    onPress={() => this._iconLeftPress()}
                >
                    <Image source={leftIcon}
                        style={[styles.leftIconStyle, { width: showTwoLine ?  marqueeStyle.marqueeTwoLeftIconSize : marqueeStyle.marqueeLeftIconSize, height: showTwoLine ? marqueeStyle.marqueeTwoLeftIconSize : marqueeStyle.marqueeLeftIconSize }]} />
                </TouchableHighlight>
            </View>);
        } else {
            if (showClose || rightIcon) {
                scrollWidth = scrollWidth - 70;
                conStyle.push({ justifyContent: 'flex-end' });
            } else {
                scrollWidth = scrollWidth - 30;
                conStyle.push({ justifyContent: 'center' });
            }
        }
        bgView.push({ width: scrollWidth });

        //滚动区域内容
        let scrollArea = [];
        let overflowStyle = Platform.OS === 'web' ? {} : { overflow: 'scroll' };
        let textSub;
        //文本滚动
        if (text) {
            if (direction == "level") {
                if (text.length > 5) {
                    text = text.slice(0, 5)
                }
                text.map((item, index) => {
                    scrollArea.push(
                        clickDisable ?
                            <TouchableHighlight underlayColor='transparent'>
                                <View style={{ flexDirection: 'row', height: 20, justifyContent: 'center', marginVertical: 12, marginRight: 16 }}>
                                    <Label text={item} type={"form"} textAlign={'center'} labelStyle={[{color:textColor ? textColor : marqueeStyle.marqueeTextColor,width:'100%'},{fontSize: titleFontSize? titleFontSize : marqueeStyle.marqueeFontSize,fontFamily:fontFamily,fontWeight:fontWeight},titleStyle]} onLayout={(event) => { this.textLayout(event)}} />
                                </View>
                            </TouchableHighlight>
                            :
                            <TouchableOpacity key={'level' + index} activeOpacity={0.7} onPress={() => this._textFunc(index)}>
                                <View style={{ flexDirection: 'row', height: 20, justifyContent: 'center', marginVertical: 12, marginRight: 16 }}>
                                    <Label text={item} type={"form"} textAlign={'center'} labelStyle={[{color:textColor ? textColor : marqueeStyle.marqueeTextColor,width:'100%'},{fontSize:titleFontSize? titleFontSize : marqueeStyle.marqueeFontSize,fontFamily:fontFamily,fontWeight:fontWeight},titleStyle]} onLayout={(event) => { this.textLayout(event)}} />
                                </View>
                            </TouchableOpacity>
                    )
                })
                if (!scroll) {
                    bgView.push({ justifyContent: 'center' });
                }
            } else if (direction == "vertical") {
                if (!showTwoLine) {
                    for (let i = 0; i < text.length; i++) {
                        scrollArea.push(
                            <View key={"vert" + i} style={{ height: 20, alignItems: 'center', flexDirection: 'row', marginVertical: 12 }} >
                                <Label text={text[i]} numberOfLines={1} labelStyle={{ color: textColor ? textColor : marqueeStyle.marqueeTextColor, fontSize: titleFontSize ? titleFontSize : marqueeStyle.marqueeFontSize }} onPress={() => this._textFunc(i)} />
                            </View>
                        );
                    }
                    //在最后一条后面额外加上第一条内容，保证切换平滑
                    scrollArea.push(
                        <View key={"vert"} style={{ height: 20, alignItems: 'center', flexDirection: 'row', marginVertical: 12 }}>
                            <Label text={text[0]} numberOfLines={1} type={"form"} labelStyle={{ color: textColor ? textColor : marqueeStyle.marqueeTextColor, fontSize: titleFontSize ? titleFontSize : marqueeStyle.marqueeFontSize }} onPress={() => this._textFunc(0)} />
                        </View>
                    );
                } else {
                    for (let i = 0; i < text.length; i = i + 2) {
                        scrollArea.push(
                            <View key={"vert" + i} style={{ height: 44, marginVertical: 10 }}>
                                <View style={{ height: 18, alignItems: 'center', flexDirection: 'row' }}>
                                    <Label text={text[i]} numberOfLines={1} labelStyle={{ color: textColor ? textColor : marqueeStyle.marqueeTwoTextColor , fontSize: marqueeStyle.marqueeTwoFontSize }} onPress={() => this._textFunc(i)} />
                                </View>
                                <View style={[{ marginTop: 8, height: 18, alignItems: 'center', flexDirection: 'row' }, overflowStyle]}>
                                    <Label text={text[i + 1]} numberOfLines={1} labelStyle={{ color: textColor ? textColor: marqueeStyle.marqueeTwoTextColor, fontSize: marqueeStyle.marqueeTwoFontSize }} onPress={() => this._textFunc(i + 1)} />
                                </View>
                            </View>
                        );
                    }
                    //在最后一条后面额外加上第一条内容，保证切换平滑
                    scrollArea.push(
                        <View key={"vert-"} style={{ height: 44, marginVertical: 10 }}>
                            <View style={{ height: 18, alignItems: 'center', flexDirection: 'row' }}>
                                <Label text={text[0]} numberOfLines={1} labelStyle={{ color: textColor ? textColor :marqueeStyle.marqueeTwoTextColor, fontSize:marqueeStyle.marqueeTwoFontSize }} onPress={() => this._textFunc(0)} />
                            </View>
                            <View style={{ marginTop: 8, height: 18, alignItems: 'center', flexDirection: 'row' }}>
                                <Label text={text[1]} numberOfLines={1} labelStyle={{ color: textColor ? textColor : marqueeStyle.marqueeTwoTextColor, fontSize:marqueeStyle.marqueeTwoFontSize }} onPress={() => this._textFunc(1)} />
                            </View>
                        </View>
                    );
                    bgView.push({ height: marqueeStyle.marqueeTwoHeight});
                }
                bgView.push({ flexDirection: "column" });
                bgView.push({ overflow: "hidden" });
            }
            //自定义组件滚动    
        } else if (scrollComponent) {
            if (direction == "level") {
                if (scrollComponent.length > 5) {
                    scrollComponent = scrollComponent.slice(0, 5)
                }
                for (let i = 0; i < scrollComponent.length; i++) {
                    scrollArea.push(
                        <View key={"level" + i} style={{ height: 20, justifyContent: 'center', marginVertical: 12, marginRight: 16 }}>
                            <View onLayout={(event) => { this.textLayout(event)}}>{scrollComponent[i]}</View>
                        </View>
                    );
                }
            } else if (direction == "vertical") {
                if (!showTwoLine) {
                    scrollArea = scrollComponent;
                } else {
                    for (let i = 0; i < scrollComponent.length; i = i + 2) {
                        scrollArea.push(
                            <View key={"vert" + i} style={{ height: 44, marginVertical: 10 }}>
                                <View>{scrollComponent[i]}</View>
                                {scrollComponent[i + 1]}
                            </View>
                        );
                    }
                    //在最后一条后面额外加上第一条内容，保证切换平滑
                    scrollArea.push(
                        <View key={"vert-"} style={{ height: 44, marginVertical: 10 }}>
                            <View>{scrollComponent[0]}</View>
                            {scrollComponent[1]}
                        </View>
                    );
                    bgView.push({ height: marqueeStyle.marqueeTwoHeight });
                }
                bgView.push({ flexDirection: "column" });
                bgView.push({ overflow: "hidden" });
            }
        }

        //右侧图标区域
        let rightArea;
        let rightIconCon = [styles.rightIconCon];
        if (showClose) {
            rightArea = (<View style={rightIconCon}>
                <TouchableHighlight underlayColor='transparent' activeOpacity={0.7}
                    onPress={() => this._close()}
                >
                    <Image source={require('../../assets/icon_marquee_nav_close.png')}
                        style={styles.rightIconStyle} />
                </TouchableHighlight>
            </View>);
        } else if (rightIcon) {
            rightArea = (<View style={rightIconCon}>
                <TouchableHighlight underlayColor='transparent' activeOpacity={0.7}
                    onPress={() => this._iconRightPress()}
                >
                    <Image source={rightIcon}
                        style={styles.rightIconStyle} />
                </TouchableHighlight>
            </View>);

        }

        return (
            <View>
                {isClose ? <View />
                    : <View style={[conStyle, titleContainerStyle]}>
                        {leftArea}
                        <View style={bgView}
                            onLayout={(event) => {
                                if (direction == 'level') {
                                    return this.bgViewWOnLayout(event);
                                }
                            }}>
                            <Animated.View
                                style={[{ transform: direction == 'level' ? [{ translateX: translateX }] : [{ translateY: translateY }] }, { flexDirection: direction == 'level' ? 'row' : 'column' }]}
                                onLayout={(event) => {
                                    // 如果动画已经开始，则不在执行动画事件
                                    if(this.animationRunning)return
                                    if (direction == 'level') {
                                        return this.textWOnLayout(event);
                                    } else if (direction == 'vertical') {
                                        return this.textHOnLayout(event);
                                    }
                                }}
                            >
                                {scrollArea}
                            </Animated.View>
                        </View>
                        {rightArea}
                    </View>}
            </View>


        );
    }
}

Marquee.propTypes = {

    //是否滚动
    scroll: PropTypes.bool,
    //滚动方向
    direction: PropTypes.string,
    //滚动文本
    text: PropTypes.array,
    //滚动组件
    scrollComponent: PropTypes.array,
    //滚动文本操作
    textFunc: PropTypes.func,
    //文本颜色
    textColor: PropTypes.string,
    //背景颜色
    backgroundColor: PropTypes.string,
    //左侧Icon
    leftIcon: PropTypes.any,
    //左侧Icon绑定的操作
    leftIconFunc: PropTypes.func,
    //右侧Icon
    rightIcon: PropTypes.any,
    //右侧Icon绑定的操作
    rightIconFunc: PropTypes.func,
    //是否显示分割线
    showLine: PropTypes.bool,
    //是否显示关闭按钮
    showClose: PropTypes.bool,
    //上下滚动是否分两行显示
    showTwoLine: PropTypes.bool,
    //滚动一次所需时间
    duration: PropTypes.number,
    //两次滚动之间延迟时间
    delay: PropTypes.number,

    //外部框宽度
    conWidth: PropTypes.number,
    //水平时，字体大小
    titleFontSize: PropTypes.number,
    //水平时，字体
    fontFamily: PropTypes.string,
    //指定本动画是否存在
    isInteraction: PropTypes.bool,
    //水平时，点击事件禁用
    clickDisable: PropTypes.bool
}

Marquee.defaultProps = {
    direction: 'level',
    backgroundColor: Color.white,
    // textColor: Color.marquee.text,
    scroll: true,
    showLine: false,
    showClose: false,
    showTwoLine: false,
    // conWidth: Dimensions.get('window').width,
    // titleFontSize: FontSize.marquee.titleFontSize,
    isInteraction: false,
    clickDisable: false
}




